#include <iostream>
#include <string>
#include <cstring> // For memset
#include "Sock.hpp"

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " IP PORT" << std::endl;
        return 1;
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 1. 创建套接字
    int clientSock = Sock::Socket();
    if (clientSock < 0) {
        std::cerr << "Socket creation error" << std::endl;
        return 1;
    }

    // 2. 连接服务器
    if(!Sock::Connect(clientSock, ip, port))
    {
        std::cerr << "Connect error" << std::endl;
        return 1;
    }

    std::cout << "Connected to server successfully." << std::endl;

    // 3. 发送数据
    std::string msg;
    std::cout << "Enter message to send to server: ";
    std::getline(std::cin, msg);
    ssize_t sentSize = send(clientSock, msg.c_str(), msg.length(), 0);
    if (sentSize < 0) {
        std::cerr << "Send error" << std::endl;
        return 1;
    }

    // 4. 接收数据
    char buffer[1024];
    memset(buffer, 0, sizeof(buffer)); // Ensure buffer is clean
    ssize_t recvSize = recv(clientSock, buffer, sizeof(buffer) - 1, 0);
    if(recvSize > 0) {
        buffer[recvSize] = '\0';
        std::cout << "Received message from server: " << buffer << std::endl;
    } else if(recvSize == 0) {
        std::cout << "Server closed connection." << std::endl;
    } else {
        std::cerr << "Receive error" << std::endl;
    }
    
    // 5. 关闭连接
    close(clientSock);

    return 0;
}
